import json
import time
import traceback

from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
from django.core.cache import cache
from django.core.paginator import Paginator
from django.shortcuts import render
# Create your views here.
from django.utils.decorators import method_decorator
from rest_framework.response import Response
from rest_framework.views import APIView

from logsManage.views import set_server_logs
from merchant.seriallizers import MerchantInfoSeriallizer

from tools.authToken import create_token, userAuth, userCateAuth
from tools.encryption import getSha256, getDataAes, setDataAes
from tools.log import logger
from tools.tool import get_ip, get_json_values, get_file_type, get_time_uid, delete_file, imgType_list
from merchant import models

from Wchime import settings


class Merchant(APIView):

    # @method_decorator(userCateAuth)
    @method_decorator([userAuth, userCateAuth])
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            userinfo = kwargs.get('userinfo')
            user_id = userinfo.get('id')
            ip = get_ip(request)
            body = request.query_params.dict()
            merchants = models.MerchantInfo.objects.filter(master_id=user_id)

            # page_size = get_json_values("page_size", body, 10)
            # page_num = get_json_values("page_num", body, 1)

            # paginator = Paginator(goods, page_size)
            # goods = paginator.get_page(page_num)
            # total = paginator.count

            seriallizer = MerchantInfoSeriallizer(merchants, many=True)
            resp = {"code": 1, "data": seriallizer.data}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth, userCateAuth])
    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            userinfo = kwargs.get('userinfo')
            user_id = userinfo.get('id')
            ip = get_ip(request)
            # body = request.POST.dict()
            body = json.loads(request.body)
            # body = request.POST.dict()
            name = get_json_values("name", body)
            describe = get_json_values("describe", body, None)
            address = get_json_values("address", body, None)
            tel = get_json_values("tel", body, None)
            # shelf = get_json_values("shelf", body, 0)
            # img = request.FILES.get("img", None)
            # filepath = None
            # icon_type = ''
            # file_name = ''
            # if img:
            #     file_nem, file_type = get_file_type(str(img))
            #     if file_type not in imgType_list:
            #         li.append('不支持该格式')
            #         resp = {"success": 0, "data": li}
            #         return Response(resp)
            #     file_name = get_time_uid()
            #     filepath = '/{}/{}/{}'.format('media', 'merchant', file_name + file_type)
            #     openfile = settings.MEDIA_ROOT + '/merchant/' + file_name + file_type
            #     with open(openfile, 'wb+') as temp_file:
            #         for chunk in img.chunks():
            #             temp_file.write(chunk)

            if models.MerchantInfo.objects.create(
                    name=name,
                    describe=describe,
                    master_id=user_id,
                    address=address,
                    tel=tel,
            ):

                resp = {"code": 1, "data": li, "msg": '新建成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '新建失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth, userCateAuth])
    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            body = json.loads(request.body)
            # body = request.POST.dict()
            id = get_json_values("id", body)
            name = get_json_values("name", body)
            address = get_json_values("address", body, None)
            describe = get_json_values("describe", body, None)

            tel = get_json_values("tel", body, None)


            # file = request.FILES.get("img", None)
            # path = get_json_values("path", body, None)
            # filepath = None
            # icon_type = ''
            # file_name = ''

            # if file:
            #     merchantImg = models.MerchantImg.objects.filter(path=path)
            #     file_nem, file_type = get_file_type(str(file))
            #     if file_type not in imgType_list:
            #         li.append('不支持该格式')
            #         resp = {"success": 0, "data": li}
            #         return Response(resp)
            #     if merchantImg:
            #
            #         filepath = path
            #         openfile = settings.BASE_DIR + path
            #         with open(openfile, 'wb') as temp_file:
            #             for chunk in file.chunks():
            #                 temp_file.write(chunk)
            #
            #         merchantImg.update(
            #             path=filepath
            #         )
            #         resp = {"code": 1, "data": li, "msg": '修改成功'}
            #         return Response(resp)
            #     else:
            #         file_name = get_time_uid()
            #         filepath = '/{}/{}/{}'.format('media', 'merchant', file_name + file_type)
            #         openfile = settings.MEDIA_ROOT + '/merchant/' + file_name + file_type
            #         with open(openfile, 'wb') as temp_file:
            #             for chunk in file.chunks():
            #                 temp_file.write(chunk)
            #
            #         item = models.MerchantImg.objects.create(
            #             path=filepath
            #         )
            #         info = models.MerchantInfo.objects.filter(id=id).last()
            #         if info:
            #             info.img.add(item.id)
            #             info.save()
            #         resp = {"code": 1, "data": li, "msg": '修改成功'}
            #         return Response(resp)
            item = models.MerchantInfo.objects.filter(id=id)
            if item.update(
                    name=name,
                    address=address,
                    describe=describe,
                    tel=tel,
            ):
                resp = {"code": 1, "data": li, "msg": '修改成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '修改失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth, userCateAuth])
    def delete(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = json.loads(request.body)
            id_list = get_json_values("id", body)
            # print(id_list)
            goods = models.MerchantInfo.objects.filter(id__in=id_list)
            goods.delete()

            resp = {"code": 1, "data": li, "msg": "删除成功"}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

